import axios from 'axios'
export default {
  namespaced: true,
  state () {
    return {
      list: []
    }
  },
  actions: {
    async aGetList (context) {
      const res = await axios.get('http://localhost:3000/cart')
      context.commit('getList', res.data)
    },
    async changeCountA (context, obj) {
      await axios.patch(`http://localhost:3000/cart/${obj.id}`, {
        count: obj.newCount
      })
      context.commit('changeCount', obj)
    }
  },
  mutations: {
    getList (state, newValue) {
      state.list = newValue
    },
    changeCount (state, newValue) {
      const shop = state.list.find(item => item.id === newValue.id)
      shop.count = newValue.newCount
    }
  },
  getters: {
    totalCount (state) {
      return state.list.reduce((acc, curr) => {
        return acc + curr.count
      }, 0)
    },
    totalPrice (state) {
      return state.list.reduce((acc, curr) => {
        return acc + curr.price * curr.count
      }, 0)
    }
  }
}
